<template>
  <!-- 返回顶部 -->
  <div
    class="hu-back-top"
    :style="styleObj"
    :class="isShow?'hu-back-top--active':''"
    @click.stop="handleBackTopClick($event)"
  >
    <slot name="default">
      <van-icon name="back-top" />
    </slot>
  </div>
</template>

<script>
export default {
  name: "HuBackTop",
  props: {
    // 触发滚动的目标对象，支持传入选择器或 DOM 元素，默认最近的父级滚动容器
    target: {
      type: String,
      default: "",
    },
    // 距离页面右侧的距离，默认单位为 px
    right: {
      type: [String, Number],
      default: 30,
    },
    // 距离页面底部的距离，默认单位为 px
    bottom: {
      type: [String, Number],
      default: 40,
    },
    // 触发目标距离顶部 XX 高度时显示返回顶部按钮
    offset: {
      type: [String, Number],
      default: 463,
    },
    // 设置组件的 z-index 层级
    zIndex: {
      type: Number,
      default: 100,
    },
  },
  data() {
    return {
      isShow: false,
      el: null,
      timer: null,
    };
  },
  mounted() {
    // 添加监听滚动条事件
    window.addEventListener("scroll", this.handleScrollx, true);
  },
  computed: {
    styleObj() {
      return {
        right: this.right + "px",
        bottom: this.bottom + "px",
        zIndex: this.zIndex,
      };
    },
  },
  methods: {
    handleScrollx() {
      this.el = document.querySelector(".hu-back-top").parentNode;
      if (this.target) {
        this.el = document.querySelector(this.target);
      }
      // 距离顶部高度
      const height = this.el.scrollTop;
      this.isShow = height >= this.offset;
    },
    // 返回顶部
    handleBackTopClick() {
      // 给回到顶部一定过度事件
      this.timer = setInterval(() => {
        this.scrollToTop();
      }, 20);
    },
    // 滚动到顶部
    scrollToTop() {
      if (this.el.scrollTop > 0) {
        this.el.scrollTop -= 50;
      } else {
        clearInterval(this.timer);
      }
    },
  },
  beforeDestroy() {
    // 销毁定时器
    clearInterval(this.timer);
    this.timer = null;
    window.removeEventListener("scroll", this.handleScrollx, true);
  },
};
</script>

<style lang="less" scoped>
.hu-back-top {
  position: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  font-size: 20px;
  cursor: pointer;
  border-radius: 999px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.12);
  transform: scale(0);
  transition: 0.3s cubic-bezier(0.25, 0.8, 0.5, 1);
  background-color: @blue;
  color: @white;
}
.hu-back-top--active {
  transform: scale(1);
}
</style>